import { encryptionData, decryptData } from '../../../utils/encAndDes' //加密解密
const regeneratorRuntime = require('../../../utils/runtime.js')
var api = require('../../../utils/api.js')
let $ = require('../../../utils/util.js')
import BluetoothLock_lxd_a from '../../../utils/lock_lxd_a.js';
const app = getApp()
var Store = app.Store
 

Page({
  data: {
    _height: 0,
    lock:null,
    lockInfo_LXD_A:{//龙兄弟锁 A版协议
    },
    lockData: {
      lock_status:0,
      open_num:0,
      close_num:0,
      lock_name:''
    }, // 锁的详情数据
    isConnectFail: !1, // 是否连接失败
    lock_code: '', // 扫出的码 安卓的deviceId
    pwdBytes:'',
    aesKey:'',
    lockName: '', // 锁的名称
    lock_id: 0, // 锁id【用户是否有权限操作接口获取】
    cabinet_id: 0, // 电表柜id【用户是否有权限操作接口获取】 
    lock_status: false, // 锁的状态 1：开锁 2：关锁
    devices: [], // 所有搜索出来的设备列表
    connected: false, // 是否连接到蓝牙设备了
    password: '110064',   // 用户输入的密码
    TOKEN: '', // 获取TOKEN
    PWD: '303030303030', //开锁密码
    LVL: app.data.lvl, // 电量 
    RET: '', // 开锁状态返回
    CNT: 0, // 开锁次数
    TIME: '', // 最后一次关锁时间
    PMS: '', // 出厂参数
    R: '', // 锁的工作状态
    STA: '', // 锁状态，00 表示开启状态，01 表示关闭状态
    isShowFail: !1, // 是否显示失败弹框
    pre:0, // 解决初始
  },

  onLoad: async function (options) { 
    this.setData({
      _height: app.data._height,
      lock_code: Store.getState().main.lock_code,
      pwdBytes:options.pwdBytes,
      aesKey:options.aesKey,
    });
    if (!this.data.lock_code) {
      $.linkurl('/pages/index/index')
    }
 
    
   if(wx.getStorageSync('blueState')=='connected'){
     console.log('lock---',JSON.parse(wx.getStorageSync('lock')))
    this.setData({
      canWrite: true,
      connected:true,
      lock:new BluetoothLock_lxd_a(wx.getStorageSync('blueDevId')),
    })
    this.lock.getBatteryLevel(wx.getStorageSync("lockToken"))
   }else{
     
     //锁查询以及权限认证
    var res = await this._search()
    // console.log('222222222222',res)
    // 开始蓝牙搜索 
    if(res.code==200)this._STimerFn()
   }
   
  },

  async onReady(){ 
  },

  onShow(){ 
    console.log('bbbbbbbbbbbbbb',this.data.lock_code)
    this.setData({
      LVL:wx.getStorageSync('lvl'),
      lockName: wx.getStorageSync('lockName'),
      lock_status: wx.getStorageSync('lockStatus')
    })
    this.setData({
      
    })
  },

  _STimerFn(){//蓝牙搜索
    var STimerNun = 0
    //初始化连接状态 默认未连接
    this.setData({
      isConnectFail: false
    })
    //初始时 连接失败接口默认不显示
    this.closeFail()
    //循环搜索时 清除上一次的定时任务
    clearInterval(this.STimer)
    this.openBluetoothAdapter()
    //定时任务搜索
    this.STimer = setInterval(() => {
      //搜索次数定时器
      STimerNun++
      //新的流程开始前 结束上一次的流程 断开蓝牙连接 参数为断开状态
      this.closeBluetoothAdapter()
      this.openBluetoothAdapter()
      if (STimerNun > 3 && !this.data.connected) {
        clearInterval(this.STimer)
        $.toast('连接失败，请重试')
        this.setData({
          isConnectFail: true
        })
        this.openFail()
      }
    }, 10000) 
  },

  openFail(){ // 开始失败弹框
    this.setData({
      isShowFail: true
    })
  },

  closeFail() { // 关闭失败弹框
    this.setData({
      isShowFail: false
    })
  },

  canclFail(){ // 点击了取消
    this.closeFail()
    $.linkurl('', 'back')
  },
  ab2hex(buffer) {
    return Array.prototype.map.call(new Uint8Array(buffer), bit => ('00' + bit.toString(16)).slice(-2)).join('');
  },

  _search() { // 用户是否有权限操作
    console.log('-------------------')
    return new Promise((resolve, reject) => { 
      api.$get(api.lockManage.lockSearch, { 
        lockId: this.data.lock_code,
      }).then((res) => {
        // console.log(res,'1111111111111111111')
        if(res.code==200){
          this.setData({
            'lockData.lock_status': res.data.lockStatus,
            'lockData.close_num': res.data.closeNum,
            'lockData.open_num': res.data.openNum,
          })
          resolve(res)
        }else if(res.code==500){
          $.linkurl(`/pages/lockMange/lockStation/lockStation?type=bind`) 
        }
      })
    })
  }, 
  
  // type 1:开  2:关
  _logadd(type){ // 蓝牙锁操作记录添加

    if (type==1){ // 开锁
      this.setData({
        'lockData.lock_status': 1,
        'lockData.open_num': this.data.lockData.open_num +1 
      })
    } else if (type==2) { // 关锁
      this.setData({
        'lockData.lock_status': 2,
        'lockData.close_num': this.data.lockData.close_num + 1
      })
    }

    wx.vibrateLong() // 震动
    console.log(type, '1: 开锁 2: 关锁')
    return new Promise((resolve, reject) => {
      app.$http.post('/lock/logadd', {
        user_id: wx.getStorageSync('user_id') || 0,
        lock_code: this.data.lock_code,
        type,
        lock_id: this.data.lockData.lock_id, // 锁id
        cabinet_id: this.data.lockData.cabinet_id, // 柜子id
      }).then(res => { 
        if (res && res.code == 0) {
          // this._search() // 初始化数据(纠正错误)
          console.log(res, '接口操作成功')
          resolve(res)
        }
      })
    })
  },

  openBluetoothAdapter(e) { // 开始扫描 
    wx.pro.openBluetoothAdapter({ // 扫描附近的蓝牙设备
      success: (res) => {
        console.log('打开蓝牙成功', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        console.log('打开蓝牙失败', res)
        $.toast('请打开蓝牙')
        if (res.errCode === 10001) {//当前蓝牙适配器不可用
          wx.pro.onBluetoothAdapterStateChange((res) => {//蓝牙适配器状态变化事件
            console.log(res.available, '##')
            if (res.available) {//蓝牙适配器是否可用
              this.startBluetoothDevicesDiscovery()//开始搜寻附近的蓝牙外围设备
            }
          })
        }
      },
      complete:(res)=>{
        console.log()
      }
    })
  },
  getBluetoothAdapterState() {
    wx.pro.getBluetoothAdapterState({ //获取本机蓝牙适配器状态。
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {//是否正在搜索设备
          this.onBluetoothDeviceFound()//监听搜索到新设备的事件
        } else if (res.available) {//蓝牙适配器是否可用
          this.startBluetoothDevicesDiscovery()//开始搜寻附近的蓝牙外围设备
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() { // 开始搜寻附近的蓝牙外围设备
    if (this._discoveryStarted) {
      return
    }
   
    this._discoveryStarted = true
    console.log('开始搜索附近的蓝牙')
    wx.pro.startBluetoothDevicesDiscovery({ // 开始搜寻附近的蓝牙外围设备
      // services: ['FEE7'],
      // allowDuplicatesKey: true,
      success: (res) => {
        console.log(res, 'FEE7')
        this.onBluetoothDeviceFound()
      },
      complete: (res) =>{
        console.log(res, '')
      }
    })
  },

  stopBluetoothDevicesDiscovery() {
    wx.pro.stopBluetoothDevicesDiscovery() // 停止搜索周边的蓝牙
  },

  _advertisData(advertisData){ // 获取小程序的广播数据
    var buff = advertisData.slice(2, 8);
    var arrayBuff = Array.prototype.map.call(new Uint8Array(buff), x => ('00' + x.toString(16)).slice(-2)).join('');
    // var arrayBuff = Array.prototype.map.call(new Uint8Array(buff), x => ('00' + x.toString(16)).slice(-2)).join(':'); // 测试用的

    console.log(arrayBuff.toUpperCase(), '广播数据')
    return arrayBuff.toUpperCase();
  }, 

  onBluetoothDeviceFound() { // 成功返回附近的蓝牙设备
    console.log('搜索设备列表')
    wx.onBluetoothDeviceFound((res) => {
      console.log(res, '返回所有设备列表')
      this.setData({
        devices: res.devices
      })
      res.devices.forEach(device => { 
        if (this._advertisData(device.advertisData) == this.data.lock_code) { // 判断锁的id是否对应上了 
          clearInterval(this.STimer) // 清除搜索定时器（好坑要不停的搜索））
          console.log(this._advertisData(device.advertisData),$.buf2hex(device.advertisData) , '是广播数据16进制')
          this.createBLEConnection(device)
          this.setData({
            isConnectFail: false
          })
          this.closeFail() 
          return
        }
      })
    })
  },
  createBLEConnection(device) { // 点击开始连接设备 
    const deviceId = device.deviceId // 设备id
    const lockName = device.name // 设备名称
    const localName = device.localName // 当前蓝牙设备的广播数据段中的 LocalName 数据段
    this.setData({
      "lockType":3,//龙兄弟锁 A版协议
      "lock":new BluetoothLock_lxd_a(deviceId,$.getbyteArray(this.data.aesKey),$.getbyteArray(this.data.pwdBytes)),
    });
    wx.pro.createBLEConnection({ // 链接低功耗设备
      deviceId,
      success: (res) => {
        this.setData({
          connected: true, // 链接成功了
          lockName,
          deviceId,
          serviceId: this.data.lock.serviceId,
          characteristicId: this.data.lock.characteristicId,
          wcharacteristicId: this.data.lock.wcharacteristicId, // 监听特征值的ID
        }) 
        Store.dispatch({
          type: 'UPDATE_CONNECTED',
          connected: true
        })
        this._getBluetoothDevices(deviceId)
        
      }
    })
    this.stopBluetoothDevicesDiscovery() // 停止搜寻附近的蓝牙外围设备(搜索成功后停止搜索附近的蓝牙设备)
  },
  closeBLEConnection() {
    //断开蓝牙连接
    wx.pro.closeBLEConnection({
      deviceId: wx.getStorageSync('blueDevId') 
    })
    this.setData({
      connected: false,
      canWrite: false,
    })
    Store.dispatch({
      type: 'UPDATE_CONNECTED',
      connected: false
    })
  },
  _getBluetoothDevices(deviceId){ 
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: (serRes) => {
        console.log('获取设备服务成功', serRes.services);
        // 假设你知道要使用的服务 UUID，这里可以根据 UUID 进行筛选
        const targetService = serRes.services.find((service) => service.uuid === this.data.serviceId);
        if (targetService) {
          this.setData({ serviceId: targetService.uuid });
          this._getBLEDeviceCharacteristics(deviceId,targetService.uuid)
        }
      },
      fail: (err) => {
        console.error('获取设备服务失败', err);
      },
    });

  }, 
  _getBLEDeviceCharacteristics(deviceId,serviceId){
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success: (charRes) => {
        // 假设你知道要使用的特征值 UUID，这里可以根据 UUID 进行筛选
        const targetCharacteristic = charRes.characteristics.find((characteristic) => characteristic.uuid === this.data.wcharacteristicId);
        if (targetCharacteristic) {
          this._notifyBLECharacteristicValueChange(deviceId,serviceId,targetCharacteristic.uuid)
        }
      },
      fail: (err) => {
        console.error('获取设备特征值失败', err);
      },
    });
  },
  _notifyBLECharacteristicValueChange(deviceId,serviceId,characteristicId){
    wx.notifyBLECharacteristicValueChange({
      state: true, // 开启通知
      deviceId,
      serviceId,
      characteristicId,
      success: (res) => {
        console.log('特征值通知已开启', res);
        this.data.lock.deviceId=deviceId;
        this.setStorage(); // 保存连接的设备信息到存储
        // 监听蓝牙设备特征值变化
        wx.onBLECharacteristicValueChange((e) => {
          const receivedData = this.ab2hex(e.value); // 将 ArrayBuffer 转换为字符串
          console.log('收到蓝牙消息（转换后）：', receivedData);
          var data= new Uint8Array(e.value);
          console.log( this.data.lock.parseBluetoothResponse(data))
          const blueData=this.data.lock.parseBluetoothResponse(data)
          if(blueData.lvl){
            app.data.lvl=blueData.lvl
            this.data.lock.queryLockStatus(wx.getStorageSync("lockToken"))
            this.setData({
              LVL: blueData.lvl
            })
            // if(blueData.locked){
            //   lock_status: blueData.locked
            // }
          }
        });
        this.setData({
          canWrite: true
        })
        this.data.lock.getToken();  //5s内未发送消息，锁具会主动断开连接
      },
      fail: (err) => {
        console.error('特征值通知开启失败', err);
      }
    });
  },



  // 开锁
  unlock() {
    const { lock, password } = this.data;
    if (password.length === 6) {
      lock.unlock("00000001",wx.getStorageSync("lockToken"));
      this.setData({
        'lockData.lock_status': 1,
        'lockData.open_num': this.data.lockData.open_num +1 
      })
      api.$get(api.lockManage.logAdd, {
        lockId: this.data.lock_code,
        type:1
      }).then(resInfo => {
      })
    } else {
      wx.showToast({ title: '请输入6位密码', icon: 'none' });
    }
  },
  // 关锁
  lock() {
    const { lock, password } = this.data;
    lock.lock(wx.getStorageSync('lockToken'));  // 流水号可传1
    this.setData({
      'lockData.lock_status': 2,
      'lockData.close_num': this.data.lockData.close_num + 1
    })
    api.$get(api.lockManage.logAdd, {
      lockId: this.data.lock_code,
      type:2
    }).then(resInfo => {
    })
  },
  _getValue() {
    wx.pro.readBLECharacteristicValue({ // 读取低功耗蓝牙设备的特征值的二进制数据值
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._read_uuid,
      success: (res) => {
        console.log(res, '蓝牙设备读出来的数据')
      },
      fail: function (res) {
        console.log(res, '!!读取蓝牙数据失败!!')
      }
    })
  },
  closeBluetoothAdapter() { // 结束流程
    this.closeBLEConnection()
    wx.pro.closeBluetoothAdapter() 
    this._discoveryStarted = false
    this.setData({
      connected: false,  
    })
    this.clearStorage();
    Store.dispatch({
      type: 'UPDATE_CONNECTED',
      connected: false
    })
  },
  // 设置本地存储
  setStorage() {
    wx.setStorageSync('lock', this.data.lock);
    wx.setStorageSync('lockInfo_LXD_A', this.data.lockInfo_LXD_A)
  },

  // 清空本地存储
  clearStorage() {
    wx.setStorageSync('lock', null);
    wx.setStorageSync('lockInfo_LXD_A', null)
  },
  onUnload(){
    console.log('整个搜索流程结束')
    this.closeBluetoothAdapter() 
    clearInterval(this.STimer) 
    clearInterval(this.TokenTime)
  },

  onHide(){
    console.log('页面关闭')
    this.closeBluetoothAdapter()
    clearInterval(this.STimer) 
    clearInterval(this.TokenTime)
  }

})
